<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <div class="logo">
          <LoginIcon />
        </div>
        <h2>欢迎回来</h2>
        <p class="subtitle">请登录您的账户</p>
      </div>
      <div class="auth-content">
        <form @submit.prevent="handleLogin" class="auth-form">
          <div class="form-group">
            <label for="login-phone">手机号</label>
            <div class="input-wrapper">
              <input 
                id="login-phone" 
                type="tel" 
                v-model="loginForm.phone" 
                placeholder="请输入11位手机号" 
                required
                pattern="[0-9]{11}"
                @input="validatePhone"
              >
            </div>
            <span class="error-message" v-if="phoneError">{{ phoneError }}</span>
          </div>
          
          <div class="form-group">
            <label for="login-password">密码</label>
            <div class="input-wrapper with-suffix">
              <input 
                id="login-password" 
                :type="showPassword ? 'text' : 'password'" 
                v-model="loginForm.password" 
                placeholder="请输入密码" 
                required
                minlength="6"
              >
              <button type="button" class="toggle-password" @click="showPassword = !showPassword">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path v-if="showPassword" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                  <circle v-if="showPassword" cx="12" cy="12" r="3"></circle>
                  <path v-else d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"></path>
                  <line v-else x1="1" y1="1" x2="23" y2="23"></line>
                </svg>
              </button>
            </div>
            <span class="error-message" v-if="passwordError">{{ passwordError }}</span>
          </div>

          <div class="form-options">
            <label class="remember-me">
              <input type="checkbox" v-model="loginForm.remember">
              <span class="checkmark"></span>
              记住我
            </label>
            <button type="button" class="forgot-password" @click.stop="handleForgotPassword">忘记密码?</button>
          </div>

          <button type="submit" class="submit-btn" :disabled="isLoading || !formValid">
            <span v-if="!isLoading">登录</span>
            <span v-else class="loading-spinner"></span>
          </button>
        </form>

        <!-- 忘记密码表单 -->
        <div v-if="showForgotPassword" class="forgot-password-modal">
          <div class="modal-overlay" @click="showForgotPassword = false"></div>
          <div class="forgot-password-form">
            <div class="form-header">
              <h3>重置密码</h3>
              <button class="close-btn" @click="showForgotPassword = false">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>

            <form @submit.prevent="handleResetPassword">
              <div class="form-group">
                <label for="reset-email">邮箱</label>
                <input 
                  id="reset-email" 
                  type="email" 
                  v-model="resetPasswordForm.email" 
                  placeholder="请输入注册邮箱" 
                  required
                  @input="validateEmail"
                >
                <span class="error-message" v-if="emailError">{{ emailError }}</span>
              </div>

              <div class="form-group">
                <label for="reset-code">验证码</label>
                <div class="input-wrapper with-button">
                  <input 
                    id="reset-code" 
                    type="text" 
                    v-model="resetPasswordForm.code" 
                    placeholder="请输入验证码" 
                    required
                  >
                  <button 
                    type="button" 
                    class="code-btn" 
                    @click="sendVerificationCode" 
                    :disabled="isSendingCode || !isEmailValid"
                  >
                    <span v-if="!isSendingCode">{{ codeBtnText }}</span>
                    <span v-else class="loading-spinner small"></span>
                  </button>
                </div>
              </div>

              <div class="form-group">
                <label for="new-password">新密码</label>
                <input 
                  id="new-password" 
                  type="password" 
                  v-model="resetPasswordForm.newPassword" 
                  placeholder="请输入新密码" 
                  required
                  minlength="6"
                  @input="validateNewPassword"
                >
                <span class="error-message" v-if="newPasswordError">{{ newPasswordError }}</span>
              </div>

              <div class="form-group">
                <label for="confirm-password">确认新密码</label>
                <input 
                  id="confirm-password" 
                  type="password" 
                  v-model="resetPasswordForm.confirmPassword" 
                  placeholder="请再次输入新密码" 
                  required
                  @input="validateConfirmPassword"
                >
                <span class="error-message" v-if="confirmPasswordError">{{ confirmPasswordError }}</span>
              </div>

              <div class="form-actions">
                <button type="button" class="cancel-btn" @click="showForgotPassword = false">取消</button>
                <button type="submit" class="submit-btn" :disabled="isResetting || !resetFormValid">
                  <span v-if="!isResetting">确认重置</span>
                  <span v-else class="loading-spinner"></span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import LoginIcon from '@@/icons/loginIcon'
import { get, post } from '@/axios'
import { userTokenStore, userInfoStore } from '@/stores'
import { ref, computed, reactive } from 'vue'
import router from '@/router'
const tokenStore = userTokenStore()
const userStore = userInfoStore()

// 登录表单相关状态
const showForgotPassword = ref(false)
const showPassword = ref(false)
const isLoading = ref(false)
const isResetting = ref(false)
const isSendingCode = ref(false)
const countdown = ref(0)
const codeBtnText = ref('获取验证码')

const loginForm = reactive({
  phone: '',
  password: '',
  remember: false
})

const resetPasswordForm = ref({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

// 错误信息
const phoneError = ref('')
const passwordError = ref('')
const emailError = ref('')
const newPasswordError = ref('')
const confirmPasswordError = ref('')

// 表单验证状态
const formValid = computed(() => {
  return loginForm.phone && loginForm.password && !phoneError.value && !passwordError.value
})

const resetFormValid = computed(() => {
  return resetPasswordForm.value.email && 
         resetPasswordForm.value.code && 
         resetPasswordForm.value.newPassword && 
         resetPasswordForm.value.confirmPassword &&
         !emailError.value &&
         !newPasswordError.value &&
         !confirmPasswordError.value &&
         resetPasswordForm.value.newPassword === resetPasswordForm.value.confirmPassword
})

const isEmailValid = computed(() => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(resetPasswordForm.value.email) && !emailError.value
})

// 验证手机号
const validatePhone = () => {
  const phone = loginForm.phone
  if (!phone) {
    phoneError.value = '请输入手机号'
  } else if (!/^[0-9]{11}$/.test(phone)) {
    phoneError.value = '请输入有效的11位手机号'
  } else {
    phoneError.value = ''
  }
}

// 验证邮箱
const validateEmail = () => {
  const email = resetPasswordForm.value.email
  if (!email) {
    emailError.value = '请输入邮箱'
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    emailError.value = '请输入有效的邮箱地址'
  } else {
    emailError.value = ''
  }
}

// 验证新密码
const validateNewPassword = () => {
  const password = resetPasswordForm.value.newPassword
  if (!password) {
    newPasswordError.value = '请输入新密码'
  } else if (password.length < 6) {
    newPasswordError.value = '密码长度不能少于6位'
  } else {
    newPasswordError.value = ''
  }
}

// 验证确认密码
const validateConfirmPassword = () => {
  const confirmPassword = resetPasswordForm.value.confirmPassword
  if (!confirmPassword) {
    confirmPasswordError.value = '请确认密码'
  } else if (confirmPassword !== resetPasswordForm.value.newPassword) {
    confirmPasswordError.value = '两次输入的密码不一致'
  } else {
    confirmPasswordError.value = ''
  }
}

// 处理忘记密码点击
const handleForgotPassword = () => {
  showForgotPassword.value = true
}
// 登录请求
const handleLogin = async () => {
  if (!formValid.value) return
  post('/umsStudent/login', {
		username: loginForm.phone,
		password: loginForm.password
	}, content => {
		tokenStore.setToken(content)
		getUserInfo()
	})
}

function getUserInfo () {
	get('/umsStudent/getUserInfo', {}, content => {
		userStore.setUserInfo(content)
		// 跳转页面
		router.push('/')
	})
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!isEmailValid.value) return
  
  try {
    isSendingCode.value = true
    const response = await axios.post(
      '/api/umsStudent/sendVerificationCode',
      null,
      {
        params: {
          email: resetPasswordForm.value.email
        }
      }
    )
    
    if (response.data.code === 200) {
      alert('验证码已发送到邮箱: ' + resetPasswordForm.value.email)
      startCountdown()
    } else {
      throw new Error(response.data.message || '发送验证码失败')
    }
  } catch (err) {
    console.error('发送失败:', err)
    alert(err.response?.data?.message || '发送验证码失败，请检查邮箱是否正确')
  } finally {
    isSendingCode.value = false
  }
}

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  codeBtnText.value = `${countdown.value}秒后重新获取`
  
  const timer = setInterval(() => {
    countdown.value--
    codeBtnText.value = `${countdown.value}秒后重新获取`
    
    if (countdown.value <= 0) {
      clearInterval(timer)
      codeBtnText.value = '获取验证码'
    }
  }, 1000)
}

// 重置密码
const handleResetPassword = async () => {
  if (!resetFormValid.value) return
  
  try {
    isResetting.value = true
    
    // 第一步：验证验证码
    const verifyResponse = await axios.post(
      '/api/umsStudent/verifyCode',
      null,
      {
        params: {
          email: resetPasswordForm.value.email,
          code: resetPasswordForm.value.code
        }
      }
    )
    
    if (verifyResponse.data.code === 200 && verifyResponse.data.content === true) {
      // 验证码验证成功，进行密码重置
      const resetResponse = await axios.post(
        '/api/umsStudent/resetPassword',
        null,
        {
          params: {
            email: resetPasswordForm.value.email,
            newPassword: resetPasswordForm.value.newPassword
          }
        }
      )
      
      if (resetResponse.data.code === 200 && resetResponse.data.content === true) {
        alert('密码重置成功，请使用新密码登录')
        showForgotPassword.value = false
        resetPasswordForm.value = { email: '', code: '', newPassword: '', confirmPassword: '' }
      } else {
        throw new Error(resetResponse.data.message || '密码重置失败')
      }
    } else {
      throw new Error(verifyResponse.data.message || '验证码错误')
    }
  } catch (err) {
    console.error('重置失败:', err)
    alert(err.response?.data?.message || '密码重置失败')
  } finally {
    isResetting.value = false
  }
}
</script>

<style scoped>
.auth-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.auth-card {
  width: 100%;
  max-width: 28rem;
  background-color: white;
  border-radius: 1rem;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.auth-header {
  padding: 2rem 2rem 1.5rem;
  text-align: center;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-bottom: 1px solid #e2e8f0;
}

.logo {
  width: 4rem;
  height: 4rem;
  margin: 0 auto 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e0e7ff;
  border-radius: 50%;
}

.logo svg {
  width: 2rem;
  height: 2rem;
}

.auth-header h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.subtitle {
  color: #64748b;
  font-size: 0.875rem;
}

.auth-content {
  padding: 1.5rem 2rem 2rem;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-group label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #1e293b;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper.with-suffix input {
  padding-right: 2.5rem;
}

.input-wrapper.with-button input {
  padding-right: 6rem;
}

input {
  width: 100%;
  height: 2.75rem;
  padding: 0 1rem;
  font-size: 0.875rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  background-color: white;
  transition: all 0.3s;
}

input:focus {
  outline: none;
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.error-message {
  color: #ef4444;
  font-size: 0.75rem;
  margin-top: 0.25rem;
  height: 1rem;
}

.toggle-password {
  position: absolute;
  right: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.25rem;
  color: #64748b;
}

.toggle-password svg {
  width: 1.25rem;
  height: 1.25rem;
}

.form-options {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.875rem;
  padding: 0.5rem 0;
}

.remember-me {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.remember-me input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

.checkmark {
  position: relative;
  height: 1rem;
  width: 1rem;
  background-color: white;
  border: 1px solid #e2e8f0;
  border-radius: 0.25rem;
  margin-right: 0.5rem;
}

.remember-me input:checked ~ .checkmark {
  background-color: #6366f1;
  border-color: #6366f1;
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.remember-me input:checked ~ .checkmark:after {
  display: block;
}

.remember-me .checkmark:after {
  left: 0.3125rem;
  top: 0.125rem;
  width: 0.25rem;
  height: 0.5rem;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.forgot-password {
  color: #6366f1;
  text-decoration: none;
  font-weight: 500;
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  font-size: 0.875rem;
  position: relative;
  z-index: 2;
  margin-left: auto;
}

.submit-btn {
  height: 2.75rem;
  background-color: #6366f1;
  color: white;
  border: none;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background-color: #4f46e5;
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.loading-spinner {
  display: inline-block;
  width: 1.25rem;
  height: 1.25rem;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
}

.loading-spinner.small {
  width: 1rem;
  height: 1rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.forgot-password-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.forgot-password-form {
  position: relative;
  width: 100%;
  max-width: 28rem;
  background-color: white;
  border-radius: 1rem;
  padding: 1.5rem;
  z-index: 101;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.25rem;
}

.form-header h3 {
  font-size: 1.125rem;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.25rem;
  color: #64748b;
}

.close-btn svg {
  width: 1.25rem;
  height: 1.25rem;
}

.code-btn {
  position: absolute;
  right: 0.25rem;
  top: 0.25rem;
  height: 2.25rem;
  padding: 0 0.75rem;
  background-color: #e0e7ff;
  color: #6366f1;
  border: none;
  border-radius: 0.375rem;
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
}

.code-btn:hover:not(:disabled) {
  background-color: #d1d5ff;
}

.code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  gap: 0.75rem;
  margin-top: 1rem;
}

.cancel-btn {
  flex: 1;
  height: 2.75rem;
  background-color: #f1f5f9;
  color: #1e293b;
  border: none;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e2e8f0;
}
</style>
